package com.beisita.web.controller;


import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class RateLimiterController {

    //限流，1秒钟2个
    private RateLimiter limiter = RateLimiter.create(2);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/limiter")
    public String testLimiter() {
        //500毫秒内，没拿到令牌，就直接进入服务降级
        boolean tryAcquire = limiter.tryAcquire(50, TimeUnit.MILLISECONDS);
        if (!tryAcquire) {
            log.warn("进入服务降级，时间{}", simpleDateFormat.format(new Date()));
            return "当前排队人数较多，请稍后再试！";
        }
        log.info("获取令牌成功，时间{}", simpleDateFormat.format(new Date()));
        return "success";
    }
}